package com.garden.web.interceptor;

import com.garden.framework.context.UserContext;
import com.garden.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Set;

@Slf4j
public class AccessLogInterceptor extends HandlerInterceptorAdapter {

    private InterceptorHandle interceptorHandle;

    @Resource
    private UserContext userContext;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        startLog(request);
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        super.postHandle(request, response, handler, modelAndView);
    }

    //可以根据ex是否为null判断是否发生了异常，进行日志记录。
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        super.afterCompletion(request,response,handler,ex);
        endLog(response, ex);
    }

    private void startLog(HttpServletRequest request) {
        AccessLog actionLog = AccessLog.getAccessLog();
        actionLog.setStart(DateUtil.now());
        actionLog.setAction(request.getRequestURI());
        actionLog.setIp(getIp(request));
        actionLog.setSessionId(getSessionId(request));

        // 请求参数
        Map parameterMap = request.getParameterMap();
        actionLog.getRequestParam().putAll(parameterMap);
        log.debug("请求开始:" + actionLog.toString());

    }
    private void endLog(HttpServletResponse response, Exception ex) {
        AccessLog actionLog = AccessLog.getAccessLog();
        actionLog.setUserId(userContext.getCurrentUserId());
        actionLog.setEnd(DateUtil.now());
        actionLog.setExecTime(actionLog.getEnd().getTime() - actionLog.getStart().getTime());
        actionLog.setStatus(String.valueOf(response.getStatus()));
        actionLog.setException(ex == null?"":ex.getStackTrace().toString());
        log.debug("请求结束:" + actionLog.toString());

        if(interceptorHandle != null) {
            interceptorHandle.handle(actionLog);
        }
//        actionLogDao.save(actionLog);
    }

    private String getIp(HttpServletRequest request) {
        String realIp = request.getHeader("X-Real-IP");
        if (StringUtils.isBlank(realIp)) {
            realIp = request.getHeader("x-forwarded-for");
        }
        if (StringUtils.isBlank(realIp)) {
            realIp = request.getRemoteAddr();
        }
        return realIp;
    }

    private String getSessionId(HttpServletRequest request) {
        HttpSession session = request.getSession();
        return session.getId();
    }

    public InterceptorHandle getInterceptorHandle() {
        return interceptorHandle;
    }

    public void setInterceptorHandle(InterceptorHandle interceptorHandle) {
        this.interceptorHandle = interceptorHandle;
    }
}

